package com.study.common

import android.os.Build
import androidx.annotation.RequiresApi
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import com.study.common.annotation.Desc
import java.lang.reflect.Type
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter


object GSONUtil {

    @Desc("创建自定义序列化器")
    @RequiresApi(Build.VERSION_CODES.O)
    private val localDateTimeSerializer: JsonSerializer<LocalDateTime> =
        JsonSerializer { src: LocalDateTime, _: Type?, _: JsonSerializationContext? ->
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            JsonPrimitive(src.format(formatter))
        }

    @Desc("创建自定义反序列化器")
    @RequiresApi(Build.VERSION_CODES.O)
    private val localDateTimeDeserializer: JsonDeserializer<LocalDateTime> =
        JsonDeserializer { json: JsonElement, _: Type?, _: JsonDeserializationContext? ->
            val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
            LocalDateTime.parse(json.asString, formatter)
        }

    @RequiresApi(Build.VERSION_CODES.O)
    private val gson: Gson = GsonBuilder().registerTypeAdapter(
        LocalDateTime::class.java, localDateTimeSerializer
    )  // 注册序列化器
        .registerTypeAdapter(LocalDateTime::class.java, localDateTimeDeserializer)  // 注册反序列化器
        .setFieldNamingStrategy(FieldNamingPolicy.IDENTITY)
        .create();

    fun toJson() {

    }

    fun <T> fromJson(json: String?, classOfT: Class<T>): T {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            gson.fromJson(json, classOfT)
        } else {
            TODO("VERSION.SDK_INT < O")
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun <T> fromJson(json: String?, type: Type): T {
        return gson.fromJson(json, type)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun toJson(obj: Any): String {
        return gson.toJson(obj)
    }

}
